package com.example.demo.util;

import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

@Slf4j
@Component
@RequiredArgsConstructor
public class HttpSendUtil {

    @Value("${qq.base-url}")
    private String baseUrl;

    private final RestTemplate restTemplate;


    public void sendPrivateMsg(String qq, String content){
        try {
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("user_id", qq);
            JSONObject privateJson = new JSONObject();
            privateJson.put("type", "text");
            JSONObject dataJson = new JSONObject();
            dataJson.put("text", content);
            privateJson.put("data", dataJson);
            JSONArray jsonArray = new JSONArray();
            jsonArray.add(privateJson);
            jsonObject.put("message", jsonArray);
            String url = "/send_private_msg";
            log.info("请求地址：{},send_private_msg请求参数: {}", url, jsonObject.toJSONString());
            String post = restTemplate.postForObject(baseUrl + url, jsonObject, String.class);
            log.info("send_private_msg返回参数: {}", post);
            JSONObject respJson = JSONObject.parseObject(post);
            assert respJson != null;
            Integer integer = respJson.getInteger("retcode");
            if (!integer.equals(0)) {
                throw new Exception("发送失败");
            }
        } catch (Exception e) {
            log.error("发送失败", e);
        }
    }

    public void sendGroupMsg(String groupId, String content){
        try {
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("group_id", groupId);
            JSONObject groupJson = new JSONObject();
            groupJson.put("type", "text");
            JSONObject dataJson = new JSONObject();
            dataJson.put("text", content);
            groupJson.put("data", dataJson);
            JSONArray jsonArray = new JSONArray();
            jsonArray.add(groupJson);
            jsonObject.put("message", jsonArray);
            String url = "/send_group_msg";
            log.info("请求地址：{},群 {} 请求参数: {}", url, groupId,jsonObject.toJSONString());
            String post = restTemplate.postForObject(baseUrl + url, jsonObject, String.class);
            log.info("send_group_msg: {}", post);
            JSONObject respJson = JSONObject.parseObject(post);
            assert respJson != null;
            Integer integer = respJson.getInteger("retcode");
            if (!integer.equals(0)) {
                throw new Exception("发送失败");
            }
        } catch (Exception e) {
            log.error("发送失败", e);
        }
    }



}
